import multiprocessing


class DeltaPID(object):
    """增量式PID算法实现"""

    def __init__(self, model):
        self.control_dic = None
        self.model = model
        self.Kp = None
        self.Ki = None
        self.Kd = None
        self.delta_output = None
        self.d_change = None
        self.i_change = None
        self.p_change = None


        self.pid_out = 0

        self.pre_pre_error = 0
        self.pre_error = 0
        self.error = 0

        self.count = 0

    def calculate(self, target, cur_val):

        self.error = target - cur_val

        self.p_change = self.Kp * (self.error - self.pre_error)
        self.i_change = self.Ki * self.error
        self.d_change = self.Kd * (self.error - 2 * self.pre_error + self.pre_pre_error)
        self.delta_output = self.p_change + self.i_change + self.d_change
        self.pid_out += self.delta_output

        self.pre_pre_error = self.pre_error
        self.pre_error = self.error

        return self.pid_out

    def list_sum(self, list_input):
        list_sum = 0
        for i in range(len(list_input)):
            list_sum += list_input[i]

        return list_sum

    def set_pid(self):
        if self.model == 'A':
            self.Kp = float(self.control_dic['a_p'])
            self.Ki = float(self.control_dic['a_i'])
            self.Kd = float(self.control_dic['a_d'])
        elif self.model == 'V':
            self.Kp = float(self.control_dic['v_p'])
            self.Ki = float(self.control_dic['v_i'])
            self.Kd = float(self.control_dic['v_d'])
        elif self.model == 'D':
            self.Kp = float(self.control_dic['d_p'])
            self.Ki = float(self.control_dic['d_i'])
            self.Kd = float(self.control_dic['d_d'])
        else:
            self.Kp = 1.0
            self.Ki = 0.0
            self.Kd = 0.0
        print(f"PID:{self.Kp, self.Ki, self.Kd}")

    def Saturation(self, value, limit_up, limit_down):
        if value > limit_up:
            return limit_up
        elif value < limit_down:
            return limit_down
        else:
            return value

    def PID_flash(self, p, i, d):
        self.Kp = p
        self.Ki = i
        self.Kd = d

    def PID_clear(self):
        self.pre_pre_error = 0
        self.pre_error = 0
        self.error = 0
        self.pid_out = 0


if __name__ == '__main__':
    pidA = DeltaPID('A')
    x = pidA.calculate(1, 0)
    print(x)
